package cn._51doit.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.ProducerFencedException;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
/**
 * @create: 2021-10-12 10:18
 * @author: 珠穆朗玛峰顶峰的男人
 * @program: kafka_java_scala
 * 生产者开启事务
 **/
public class JavaPropertiesTransaction {
    public static void main(String[] args) {
        //配置kafka参数对象
        Properties properties = new Properties();
        // 连接kafka节点
        properties.setProperty("bootstrap.servers", "doit01:9092,doit02:9092,doit03:9092");
        //指定key序列化方式
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        //指定value序列化方式
        properties.setProperty("value.serializer", StringSerializer.class.getName());
        //如果要开启事务，必须为生产者设置一个事务ID（每一次都要有一个事务ID）
        properties.setProperty("transactional.id", "doit1123123123");

        //生产者实例
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        //初始化事务
        producer.initTransactions();
        //开启事务(要使用事务)
        producer.beginTransaction();
        try {
            //封装数据
            ProducerRecord<String, String> producerRecord1 = new ProducerRecord<>("word", "hello flink 111");
            //写数据方法
            producer.send(producerRecord1);
            //刷写到kafka
            producer.flush();
            int a=1/0;  //异常
            //封装数据
            ProducerRecord<String, String> producerRecord2 = new ProducerRecord<>("word", "hello flink 222");
            //写数据方法
            producer.send(producerRecord2);
            //提交事务
            producer.commitTransaction();
        } catch (Exception e) {
            //放弃事务
            producer.abortTransaction();
        }
        //关闭资源
        producer.close();
    }
}
